package com.shujia.base.day04

import java.util.Scanner
import scala.io.Source
import scala.language.implicitConversions

/**
 * 模式匹配，其实是一个优化写代码的一种方式
 *
 * 优点：
 * 1、可以减少代码量
 * 2、可以避免报错
 *
 * 语法：
 * 变量|对象|集合 match {
 * case 数据类型(xxx,xxx,xxx) => xxx,
 * case _:xxx
 * }
 */
object Demo26Match {
  def main(args: Array[String]): Unit = {

    //使用模式匹配，匹配一个变量值
    val i: Int = 50
    i match {
      case 50 => println("不及格")
      case 60 => println("及格")
      case 100 => println("满分")
      case _ => println("其他值")
    }

    println("=" * 50)

    //使用模式匹配，匹配一个数组
    val arr1: Array[String] = Array("hello", "world", "java")

    arr1 match {
      case Array(c1: String, c2: String, c3: String, c4: String) => println(s"c1:${c1},c2:${c2},c3:${c3},c4:${c4}")
      case Array(c1: String, c2: String, c3: String) => println(s"c1:${c1},c2:${c2},c3:${c3}")
      case _ => println("未匹配到")
    }

    println("=" * 50)
    //使用模式匹配，匹配一个类型
    val i2:Double = 12.34
    i2 match {
      case _:Double => println("是一个Double类型")
      case _ => println("其他类型")
    }

    println("=" * 50)
    //使用模式匹配，匹配一个元组
//    val t1: (Int, String, Int) = Tuple3(1001, "张三", 18)
    val t1: (Int, String, Int) = Tuple3(1001, "张三", 18)
    //元组模式匹配的时候，长度必须保持一致，若匹配的内容缺少，使用_占位符
    t1 match {
      case (id:Int,name:String,age:Int)=>println(s"学号：${id}, 姓名：${name}，年龄：${age}")
      case _ => println("为匹配成功！")
    }

    println("=" * 50)
    //使用模式匹配，可以避免报错
    val map1: Map[String, String] = Map("1001" -> "张三", "1002" -> "李四", "1003" -> "王五")
//    println(map1.get("1001").get)
//    println(map1.get("1008").get) // None值无法调用函数，报错

    val sc = new Scanner(System.in)
    println("请输入要查找的键：")
    val key: String = sc.next()
    map1.get(key) match {
      case Some(value:String) => println(s"${key}对应的值为${value}")
      case None => println("Map集合中没有对应键")
    }
    println("=" * 50)
    //使用模式匹配，可以减少代码量
    case class Student(id:String,name:String,age:String,gender:String,clazz:String)
    val studentsList: List[String] = Source.fromFile("scala/data/students.txt").getLines().toList

    //未使用模式匹配
    val students: List[Student] = studentsList.map((e: String) => {
      val info: Array[String] = e.split(",")
      val id: String = info(0)
      val name: String = info(1)
      val age: String = info(2)
      val gender: String = info(3)
      val clazz: String = info(4)
      Student(id, name, age, gender, clazz)
    })
    students.foreach(println)

    println("*"*50)
    //使用模式匹配
    val students1: List[Student] = studentsList
      .map(_.split(","))
      .map {
        case Array(id: String, name: String, age: String, gender: String, clazz: String) => Student(id, name, age, gender, clazz)
    }

    students1.foreach(println)


  }
}
